import { useRef, useState, useEffect } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Modal, message, Form, Input, Select, Button } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { activitygroupSearch, activitygroupEdit, activitygroupDelete } from '@/services/storegroup';
import StorageManager from '@/utils/StorageManager';

import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const { confirm } = Modal;

const eunmGroupTypeIdList = [
  { label: 'group1', value: 1 },
  { label: 'group2', value: 2 },
  { label: 'RSC电商', value: 3 },
  { label: 'RSC营销', value: 4 },
  { label: '市场券', value: 5 },
];

const ActivitygroupList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modalForm] = Form.useForm();
  const [valueEnumActivityId, setValueEnumActivityId] = useState({});
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelVisible, setModelVisible] = useState<boolean>(false);
  const [modelTitle, setModelTitle] = useState<string>('');
  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');

  useEffect(() => {
    const obj: any = {};
    eunmList?.OptionsPlaceBrandList.forEach((item: any) => {
      obj[item.value] = {
        text: item.label,
      };
    });
    setValueEnumActivityId({
      // ALL: { text: 'ALL' },
      ...obj,
    });
  }, []);

  // 提交
  const handleOperate = (record: any, type: string) => {
    if (type === '修改') {
      modalForm.setFieldsValue({
        ...record,
      });
      setModelTitle('修改');
      setModelVisible(true);
      return;
    }

    confirm({
      content: `确认${type} 活动组：${record.activityGroup}？`,
      async onOk() {
        try {
          const { code, data } = await activitygroupDelete({ id: record.id });
          if (code === 200 && data) {
            message.success('操作成功');
            actionRef?.current?.reloadAndRest?.();
          } else {
            message.error('解锁失败');
          }
        } catch (error) {}
      },
      onCancel() {},
    });
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      hideInTable: true,
      fieldProps: {
        placeholder: 'activityGroup',
      },
    },
    {
      title: '品牌ID',
      dataIndex: 'brandId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请选择',
      },
      valueEnum: valueEnumActivityId,
    },
    // 表格
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动组描述',
      dataIndex: 'activityGroupDesc',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '品牌ID',
      dataIndex: 'brandId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '组类型',
      dataIndex: 'groupTypeId',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '创建用户',
      dataIndex: 'createUser',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '更新用户',
      dataIndex: 'updateUser',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 200,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => handleOperate(record, '修改')}>修改</a>&nbsp;&nbsp;
            <a onClick={() => handleOperate(record, '删除')}>删除</a>&nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.ActivitygroupInfo = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await activitygroupSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleOK = () => {
    modalForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await activitygroupEdit({
        ...values,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalForm.resetFields();
        setModelVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  const handleCancel = () => {
    setModelVisible(false);
    modalForm.resetFields();
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.ActivitygroupListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [
              <Button
                type="primary"
                key="add"
                onClick={() => {
                  setModelVisible(true);
                  setModelTitle('新增');
                }}
              >
                新增
              </Button>,
              ...dom,
            ],
          }}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title={modelTitle + '活动组'}
          width={520}
          open={modelVisible}
          onOk={handleOK}
          onCancel={handleCancel}
          confirmLoading={confirmLoad}
          footer={
            <div>
              <Button
                type="primary"
                key="add1"
                onClick={() => {
                  modalForm.setFieldValue('brandId', '001');
                }}
              >
                重置
              </Button>
              <Button type="primary" key="add2" onClick={handleOK}>
                保存
              </Button>
            </div>
          }
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalForm}
            initialValues={{
              id: '',
              activityGroup: '',
              activityGroupDesc: '',
              brandId: '001',
              groupTypeId: 1,
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="活动组"
              name="activityGroup"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="activityGroup(必填)" />
            </Form.Item>
            <Form.Item
              label="活动组描述"
              name="activityGroupDesc"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input placeholder="activityGroupDesc(必填)" />
            </Form.Item>
            <Form.Item
              label="品牌ID"
              name="brandId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={eunmList?.OptionsPlaceBrandList || []} />
            </Form.Item>
            <Form.Item
              label="组类型"
              name="groupTypeId"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={eunmGroupTypeIdList} />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default ActivitygroupList;
